package com.yunxiangyue.musicplayer

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.IBinder
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.Button
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.yunxiangyue.app.R
import com.yunxiangyue.framlayoutActivity
import com.yunxiangyue.logger.Logger
import com.yunxiangyue.server.ConnectExample
import de.hdodenhof.circleimageview.CircleImageView
import java.io.*
import kotlin.concurrent.thread

class music_para(var current:String,var process:Int): Serializable {}
class music_playing : AppCompatActivity(), View.OnClickListener, ServiceConnection {
    var isPause = true
    var aixinCount = 0
    var current:Int = 0
    var count = 1
    var process = 0
    var serviceBinder: MusicService.musicBinder? = null
    var sdCardDir = Environment.getExternalStorageDirectory()
    private var musicList : ArrayList<Music> =  ArrayList()
    private val tag:String = "music_playing"



    //临时音乐存储文件
    private lateinit var tempFile:File
    private lateinit var fileUri:Uri

    private var connectExample:ConnectExample =ConnectExample()

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    @SuppressLint("UnspecifiedImmutableFlag")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_music_playing)
        val seekBar3 = findViewById<SeekBar>(R.id.seekBar3)
        val start = findViewById<Button>(R.id.start)
        val prev = findViewById<Button>(R.id.prev)
        val aixin = findViewById<Button>(R.id.aixin)
        val next = findViewById<Button>(R.id.next)
        val back_music = findViewById<Button>(R.id.back_music)
        val btnComments = findViewById<Button>(R.id.btnComments)

        startMusicService()
        supportActionBar?.hide()

        val musicName = intent.getStringExtra(INTENT_KEY_MUSIC_NAME).toString()
        val musicList = intent.getSerializableExtra(
            INTENT_KEY_MUSIC_LIST
        ) as ArrayList<Music>
        this.musicList = musicList
        Logger.debug(tag,"musicList size = ${musicList?.size}, musicName = $musicName")

        musicList.forEach {
            if(it.musicName.equals(musicName)){
                // num 从 1 开始， 需要减一从 0 开始
                current = it.num.toInt() - 1
            }
        }
        Logger.debug(tag,"current = $current, get music = ${musicList[current]}")
        process = 0

        start.setOnClickListener(this)
        prev.setOnClickListener(this)
        next.setOnClickListener(this)
        btnComments.setOnClickListener(this)
        seekBar3.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                if (p2) {
                    if (serviceBinder?.setCurrentDuration(seekBar3.progress) == false) {
                        seekBar3.progress = 0
                    }
                }
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {}
            override fun onStopTrackingTouch(p0: SeekBar?) {}
        })
        aixin.setOnClickListener {
            if (aixinCount % 2 == 0) {
                aixin.setBackgroundResource(R.drawable.ic_aixin_1)
            } else {
                aixin.setBackgroundResource(R.drawable.ic_aixin)
            }
            aixinCount++
        }
        back_music.setOnClickListener {
            val intent = Intent(this, framlayoutActivity::class.java)
            startActivity(intent)
            unbindService(this)
        }
        showImages()
    }


    fun startMusicService(){
        val intent = Intent(this,MusicService::class.java)
        startService(intent)
        bindService(intent,this,Context.BIND_AUTO_CREATE)
    }

    //从服务端获取音乐资源，并保存进临时文件
    private fun getMusicDataAndPlay(loc:Int){
        Logger.debug(tag,"调用getMusicData")
        val musicName = musicList[current].musicName
        connectExample.getMusicByName(musicName){ result,byteArray ->
            if(result) {
                Logger.debug(tag,"数据响应成功")

                showImages()
                changeStartState(true)
                anim()

                tempFile = File.createTempFile(musicName, ".mp3", this.cacheDir)
                tempFile.deleteOnExit() // 确保应用退出时删除文件
                Logger.debug(tag, "musicName = $musicName and file = $tempFile")
                fileUri = Uri.fromFile(tempFile)
                Logger.debug(tag, "musicName = $musicName uri = $fileUri")

                serviceBinder?.startNewMusic(loc, fileUri)?:Logger.error(tag, "startNewMusic failed because binder is null!")
            }else{
                Logger.debug(tag,"数据响应失败")
            }
        }
    }

    //回调函数的定义部分  获取单个音乐信息时  响应成功时才去调用startService确保传给服务的值不为空

    //这里只获取一次音乐文件

    private fun startClick() {
        if (isBind) {
            serviceBinder?.let {
                if (it.isMediaPlayerReady()) {
                    val start = findViewById<Button>(R.id.start)
                    if (count % 2 == 0) {
                        start.setBackgroundResource(R.drawable.ic_bofang)
                        it.getMusicService().pauseMusic()
                    } else {
                        start.setBackgroundResource(R.drawable.ic_bofang__1_)
                        it.getMusicService().playMusic()
                    }
                    Logger.debug(tag,"count 值为：$count")
                    count ++
                }
            }?:Logger.error(tag, "binder is null but is Bind is true!!")
        }
    }

    fun next() {
        val aixin = findViewById<Button>(R.id.aixin)
        isPause = false
        if(current == musicList.size){
            current = 0
        }else{
            current++
        }
        getMusicDataAndPlay(current)
        aixin.setBackgroundResource(R.drawable.ic_aixin)
        showImages()
        anim()
    }

    fun changeStartState(startBool: Boolean) {
        val start = findViewById<Button>(R.id.start)
        if (startBool) {
            start.setBackgroundResource(R.drawable.ic_bofang__1_)
            count = 1
        } else {
            start.setBackgroundResource(R.drawable.ic_bofang)
            count = 0
        }
    }

    fun prev() {
        val start = findViewById<Button>(R.id.start)
        val aixin = findViewById<Button>(R.id.aixin)
        isPause = false
        if(current<0){
            current  = musicList.size -1
        }else{
            current --
        }
        getMusicDataAndPlay(current)
        aixin.setBackgroundResource(R.drawable.ic_aixin)
        start.setBackgroundResource(R.drawable.ic_bofang__1_)
        count = 1
        showImages()
        anim()
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    fun showImages() {
        var images = findViewById<ImageView>(R.id.imageView)
        if (current <= 7) {
            images.setImageDrawable(resources.getDrawable(R.drawable.five))
        } else if (current >= 8 && current <= 9) {
            images.setImageDrawable(resources.getDrawable(R.drawable.two))
        } else if (current >= 10 && current <= 11) {
            images.setImageDrawable(resources.getDrawable(R.drawable.juzhihai_))
        } else if (current >= 12 && current <= 14) {
            images.setImageDrawable(resources.getDrawable(R.drawable.four))
        } else if (current >= 15 && current <= 17) {
            images.setImageDrawable(resources.getDrawable(R.drawable.one))
        } else if (current >= 18 && current <= 20) {
            images.setImageDrawable(resources.getDrawable(R.drawable.six))
        } else if (current >= 21 && current <= 22) {
            images.setImageDrawable(resources.getDrawable(R.drawable.five))
        }else if (current >= 23 && current <= 25){
            images.setImageDrawable(resources.getDrawable(R.drawable.bass1))
        }else{
            images.setImageDrawable(resources.getDrawable(R.drawable.background2))
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            androidx.appcompat.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

//    override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<out String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        if (requestCode == 1) {
//            if (grantResults.first() == PackageManager.PERMISSION_GRANTED) {
//                startBinder()
//            }
//        }
//    }

    fun anim() {
        val imageView = findViewById<CircleImageView>(R.id.imageView)
        if (!isPause) {
            var animation = AnimationUtils.loadAnimation(this, R.anim.rotate_img)
            var mode = LinearInterpolator()
            animation.setInterpolator(mode)
            //动画旋转一圈所需时间
            animation.duration = 30000
//        设置重复模式为无限次
            animation.repeatMode = Animation.RESTART
//        设置动画无限次的重复次数
            animation.repeatCount = -1
//            animation.fillAfter=false
            imageView.startAnimation(animation)
        } else {
            imageView.clearAnimation()
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.start -> startClick()
            R.id.next -> next()
            R.id.prev -> prev()
            R.id.btnComments -> {
                val intent=Intent(this, com.yunxiangyue.Comm::class.java)
                startActivity(intent)
            }
        }
    }

    override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
        serviceBinder = p1 as MusicService.musicBinder
        serviceBinder?.setMusicList(musicList)?:Logger.error(tag, "set music list failed, binder is null")
        getMusicDataAndPlay(current)
        var temp = 0
        var aixinCount = 0
        thread {
            while (serviceBinder != null) {
                Thread.sleep(100)
                runOnUiThread() {
                    serviceBinder?.also {
                        it.getMusicService().current = current
                        findViewById<TextView>(R.id.musicName).let { name ->
                            if (name.text != it.getCurrentMusicName()) {
                                name.setText(it.getCurrentMusicName())
                                findViewById<TextView>(R.id.author).setText(it.getCurrentMusicSinger())
                            }
                        }
                        val seekBar3 = findViewById<SeekBar>(R.id.seekBar3)
                        if (it.isMediaPlayerReady()) {
                            seekBar3.max = it.getMediaPlayer().duration
                            seekBar3.progress = it.getMediaPlayer().currentPosition
                            isPause = it.getMusicService().isPause
                        }
                    }
                }
            }

        }

    }
    override fun onServiceDisconnected(p0: ComponentName?) {
        serviceBinder = null
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(this)
        val intent = Intent(this,MusicService::class.java)
        stopService(intent)

    }
}



